// mock/role.ts
import LogSingleton from './log';
let createRoleList = [
	{
		roleId: 1,
		roleName: '超级管理员',
		roleSign: 'admin',
		status: 1,
	},
	{
		roleId: 2,
		roleName: '普通用户',
		roleSign: 'user',
		status: 0,
	},
];
let num = 3;
export default [
	//获取全部角色信息
	{
		url: '/api/role/getAllRole',
		method: 'post',
		response: (request: any) => {
			// 获取请求头携带的 token
			const token = request.headers.token;
			let newList: any = [];
			if (request.body.roleName) {
				newList = createRoleList.filter((item) => item.roleName.indexOf(request.body.roleName) != -1);
			} else {
				newList = createRoleList;
			}

			return {
				code: 200,
				data: newList,
			};
		},
	},
	//新增角色 / 修改
	{
		url: '/api/role/addRole',
		method: 'post',
		response: (data: any) => {
			LogSingleton.addToLogData({
				logName:'新增/修改角色',
				url: data.url,
				data: data.body,
			})
			
			if (!data.body.roleName) {
				return {
					code: 400,
					data: {
						message: '请输入角色名称',
					},
				};
			}
			if (data.body.roleId == '') {
				//新增
				data.body.roleId = num++;
				createRoleList.push(data.body);
			} else {
				//修改
				let idx = -1;
				createRoleList.map((item, index) => {
					if (item.roleId == data.body.roleId) {
						// item = data.body;
						idx = index;
					}
				});
				if (idx != -1) {
					createRoleList[idx] = data.body;
				}
			}

			const roleList = createRoleList;

			return {
				code: 200,
				data: roleList,
			};
		},
	},
	//删除角色
	{
		url: '/api/role/delRole',
		method: 'post',
		response: (data: any) => {
			LogSingleton.addToLogData({
				logName:'删除角色',
				url: data.url,
				data: data.body,
			})
			createRoleList = createRoleList.filter((item) => item.roleId !== data.body.roleId);

			return {
				code: 200,
				data: '操作成功',
			};
		},
	},
	// 获取角色信息接口
	{
		url: '/api/role/info',
		method: 'get',
		response: (request: any) => {
			// 获取请求头携带的 token
			const token = request.headers.token;
			// 查看角色信息数据中是否包含有此 token 的角色
			const checkRole = createRoleList.find((item) => item.token === token);
			// 没有就返回失败信息
			if (!checkRole) {
				return {
					code: 201,
					data: {
						message: '获取角色信息失败',
					},
				};
			}
			// 有就返回成功信息
			return {
				code: 200,
				data: {
					checkRole,
				},
			};
		},
	},
];
